package com.stone.im.geteway.tcp;

import com.stone.im.common.*;
import com.stone.im.protobuf.proto.AuthenticateRequestProto;
import com.stone.im.protobuf.proto.MessagePushResponseProto;
import com.stone.im.protobuf.proto.MessageSendRequestProto;
import com.stone.im.protobuf.proto.MessageSendResponseProto;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;
import redis.clients.jedis.Jedis;

import javax.swing.*;

public class GatewayTcpHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("已经跟客户端完成连接"+(SocketChannel)ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {

        JedisManager jedisManager=new JedisManager();
        Jedis jedis = jedisManager.getJedis();

        SocketChannel channel = (SocketChannel)ctx.channel();

        String channelId = channel.remoteAddress().getHostName() + ":" +channel.remoteAddress().getPort();

        SessionManager instance = SessionManager.getInstance();

        jedis.del("session"+instance.getUidByChannelId(channelId));
        instance.removeClient(channel);

        System.out.println("检测到断开连接，删除连接"+channel.remoteAddress().toString());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = new Message((ByteBuf) msg);

        RequestHandle requestHandle = RequestHandle.getInstance();

        System.out.println("收到一个消息，消息类型为："+message.getMessageType());
        /**
         * 如果是认证请求
         */
        if (message.getMessageType() == Constants.MESSAGE_TYPE_REQUEST){

            Request request = message.toRequest();
            if (request.getRequestType() == Constants.REQUEST_TYPE_AUTHENTICATE){

                byte[] body = request.getBody();
                //调用业务逻辑处理组件进行认证
                AuthenticateRequestProto.AuthenticateRequest authenticateResponse = AuthenticateRequestProto.AuthenticateRequest.parseFrom(body);
                //认证处理
                requestHandle.authenticate(authenticateResponse);
                //设置一下本地session
                SessionManager instance = SessionManager.getInstance();
                instance.addClient(authenticateResponse.getUid(),(SocketChannel) ctx.channel());
            }else if (message.getMessageType() == Constants.REQUEST_TYPE_SEND_MESSAGE){
                //处理单聊消息

                MessageSendRequestProto.MessageSendRequest messageSendRequest =
                        MessageSendRequestProto.MessageSendRequest.parseFrom(request.getBody());
                requestHandle.sendMessage(messageSendRequest);
                System.out.println("收到客户发送的单聊消息....");
            }
        }else if (message.getMessageType() == Constants.MESSAGE_TYPE_RESPONSE){
            Response response = message.toResponse();

            if (response.getRequestType() == Constants.REQUEST_TYPE_PUSH_MESSAGE){
                MessagePushResponseProto.MessagePushResponse messagePushResponse = MessagePushResponseProto.MessagePushResponse.parseFrom(response.getBody());
                requestHandle.pushMessageResponse(messagePushResponse);
            }
        }
    }

    protected void channelRead0(ChannelHandlerContext ctx, Object message) throws Exception {
        Channel channel = ctx.channel();//对socketchannel进行缓存，客户推送消息，直接去缓存里找socketchannel
        SessionManager instance = SessionManager.getInstance();


    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
